package ar.com.ford.it.fullEconomics.logic;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.CurrencyDao;
import ar.com.ford.it.fullEconomics.persistence.dao.EconomicIndexDefDao;
import ar.com.ford.it.fullEconomics.persistence.dao.EconomicValueDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese03Econvalue;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class EconomicValueLogic {
    private static final String CLASS_NAME = EconomicValueLogic.class.getName();

    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /***************************************************************************
     * ** ******** **********Economic Index Value**** ******* **
     **************************************************************************/
    /**
     * Finda all de economic Index Value only filter plant
     * 
     * 
     * @param plant
     * @throws FullEconomicsException
     */
    public Collection<Teese03Econvalue> findAllEconomicValue(Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "findAllEconomicValue";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teese03Econvalue> res = null;
        EconomicValueDao dao = new EconomicValueDao();
        String[] fields = { "eese03PlantCodeC" };
        Object[] values = { plant };

        try {
            res = dao.findAll(new Teese03Econvalue(), fields, values);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find all Economic Value Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.EconomicValue.FINDALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Creacion de Economic Value es indistitno si es Forcasted o Actual
     * 
     * @param ecoV
     * @param user
     * @throws FullEconomicsException
     */
    public void createEconomicValue(Teese03Econvalue ecoV,
                                    FullEconomicsWslxUser user)
            throws FullEconomicsException {
        String METHOD_NAME = "createEconomicValue";
        log.entering(CLASS_NAME, METHOD_NAME);
        EconomicValueDao dao = new EconomicValueDao();
        Teese03Econvalue ecoVRecord = new Teese03Econvalue();
        String codeCurren = ecoV.getEese03CurrencyCodeC()
                .getEesm01CurrencyCodeC();

        try {
            PersistenceUtil.newTransaction();
            ecoVRecord.setTeese01Economic((new EconomicIndexDefDao())
                    .getEconomicIndexDefForUpdate(user.getTeesg01Plant(), ecoV
                            .getTeese01Economic().getEese01EconNumberK()));
            ecoVRecord.setEese03CurrencyCodeC((new CurrencyDao())
                    .getCurrencyForUpdate(codeCurren));
            ecoVRecord.setEese03EcvalueEffectivDateY(ecoV
                    .getEese03EcvalueEffectivDateY());
            if(ecoV.getEese03EcvalueEffectivDateY().after(new Timestamp(System
                    .currentTimeMillis()))){
                ecoVRecord.setEese03EcvalueTypeCodeC("F");
                ecoVRecord.setEese03EcvalueEstimateFlagF("1");
            }else{
                ecoVRecord.setEese03EcvalueTypeCodeC(ecoV
                        .getEese03EcvalueTypeCodeC());
                ecoVRecord.setEese03EcvalueEstimateFlagF(ecoV.getEese03EcvalueEstimateFlagF());
            }
            ecoVRecord.setEese03EcvalueVariaPercentP(ecoV
                    .getEese03EcvalueVariaPercentP());
            ecoVRecord.setEese03EcvalueAmountA(ecoV.getEese03EcvalueAmountA());
            ecoVRecord.setEese03CreateUserC(user.getId());
            ecoVRecord.setEese03LastUserUpdtC(user.getId());
            ecoVRecord.setEese03PlantCodeC(user.getTeesg01Plant());
            ecoVRecord.setEese03CreateS(new Timestamp(System
                    .currentTimeMillis()));
            ecoVRecord.setEese03LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));

            dao.createEconomicValue(ecoVRecord);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {
            pe.printStackTrace();
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {

                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Economic Index Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.EconomicValue.CREATE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Actualizacion de Econmic Value
     * 
     * @param ecoV
     * @param user
     * @param codeSour
     * @param codeCurren
     * @throws FullEconomicsException
     */
    public void updateEconomicValue(Teese03Econvalue ecoV,
                                    FullEconomicsWslxUser user)
            throws FullEconomicsException {
        String METHOD_NAME = "updateEconomicValue";
        log.entering(CLASS_NAME, METHOD_NAME);
        Teese03Econvalue workingCopy = new Teese03Econvalue();
        try {
            PersistenceUtil.newTransaction();
            PersistenceUtil.getPersistenceManager().clearCache();
            workingCopy = (new EconomicValueDao()).getEcoValueForUpdate(ecoV);
            workingCopy.setEese03EcvalueAmountA(ecoV.getEese03EcvalueAmountA());
            workingCopy.setEese03EcvalueVariaPercentP(ecoV
                    .getEese03EcvalueVariaPercentP());
            workingCopy.setEese03LastUserUpdtC(user.getId());
            workingCopy.setEese03LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            workingCopy.setEese03EcvalueaApprovalUserC(null);
            workingCopy.setEese03EcvalueaApprovalUserC(null);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {

            pe.printStackTrace();
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Economic Index Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.EconomicValue.UPDATE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Elemina un economic Value
     * 
     * @param ecoV
     * @return
     * @throws FullEconomicsException
     */
    public boolean deleteEconomicValue(Teese03Econvalue ecoV)
            throws FullEconomicsException {
        String METHOD_NAME = "deleteEconomicValue";
        log.entering(CLASS_NAME, METHOD_NAME);
        boolean res = true;
        try {
            PersistenceUtil.newTransaction();
            EconomicValueDao dao = new EconomicValueDao();
            dao.deleteEconomicValue(ecoV);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException e) {
            res = false;
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find All Economic Index Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.EconomicValue.DELETE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Si el indice economic fue resgistrado envia true .. sino false Esto se
     * debe a que muestra el indice economico por pantalla el cual no este
     * registrado
     * 
     * @param ecoV
     * @return
     * @throws FullEconomicsException
     */
    public boolean ecoVRegistrationValidate(Teese03Econvalue ecoV)
            throws FullEconomicsException {

        String METHOD_NAME = "ecoVCanBeRegistration";
        log.entering(CLASS_NAME, METHOD_NAME);
        boolean resUltado = true;

        Collection<Teese03Econvalue> res = null;
        EconomicValueDao dao = new EconomicValueDao();
        String[] fields = { "eese03PlantCodeC", "teese01Economic" };
        Object[] values = { ecoV.getEese03PlantCodeC(),
                ecoV.getTeese01Economic() };

        try {
            res = dao.findAll(new Teese03Econvalue(), fields, values);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find all Economic Value Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.EconomicValue.FINDALL);
        }
        if (res.isEmpty())
            resUltado = false;
        log.exiting(CLASS_NAME, METHOD_NAME);
        return resUltado;
    }

    public boolean ecoVApprovedValidate(Teese03Econvalue ecoV,
                                        FullEconomicsWslxUser user) {

        String METHOD_NAME = "ecoVApprovedValidate";
        log.entering(CLASS_NAME, METHOD_NAME);

        boolean ret = false;
        if (ecoV.getEese03CreateUserC() != null
                && !ecoV.getEese03CreateUserC().equalsIgnoreCase(user.getId())
                && ecoV.getEese03EcvalueaApprovalUserC() == null) {
            ret = true;
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return ret;
    }

    public void approveEcoV(Teese03Econvalue ecoV, FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "approveEcoV";
        log.entering(CLASS_NAME, METHOD_NAME);

        EconomicValueDao dao = new EconomicValueDao();
        Teese03Econvalue workingCopy = null;

        try {
            PersistenceUtil.newTransaction();
            workingCopy = dao.getEcoValueForUpdate(ecoV);
            workingCopy.setEese03EcvalueApprovalS((new Timestamp(System
                    .currentTimeMillis())));
            workingCopy.setEese03EcvalueaApprovalUserC(user.getId());
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Approve Item Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Item.APPROVE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    public Collection periodEconomicValue(Teesg01Plant plant)
            throws FullEconomicsException {


        Collection<Teese03Econvalue> ecoVs = this.findAllEconomicValue(plant);
        List<OptionCombo> optCombo = new ArrayList<OptionCombo>();
        HashMap contain = new HashMap();
        OptionCombo auxOp;
        if (!ecoVs.isEmpty()) {
            for (Teese03Econvalue econValue : ecoVs) {
                auxOp = new OptionCombo();
                if(!contain.containsKey(econValue.getEese03EcvalueEffectivDateY().toString().substring(0,4))){
                optCombo.addAll(generarFechasParaAnio(econValue.getEese03EcvalueEffectivDateY().toString().substring(0,4)));
                contain.put(econValue.getEese03EcvalueEffectivDateY().toString().substring(0,4),"");
                }
            }
        }
        return optCombo;
    }

    private Collection<? extends OptionCombo> generarFechasParaAnio(String anio) {
        List<OptionCombo> colDate = new ArrayList<OptionCombo>();
        for (Integer dia = 101; dia < 113; dia ++){
            OptionCombo date = new OptionCombo(anio+"-"+dia.toString().substring(1,3),anio+"-"+dia.toString().substring(1,3));
            colDate.add(date);
        }
            

        return colDate;
    }

    public boolean economicValueIsRepeat(Teese03Econvalue ecoV) {
        EconomicValueDao dao = new EconomicValueDao();
        try {
            if (dao.getEcoValueById(ecoV) != null) {
                return true;
            }
        } catch (PersistenceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    public Collection getEconomicValuesMaxLessDate(Teese03Econvalue ecoV,
                                                   Timestamp periodSelec)
            throws FullEconomicsException {
        String METHOD_NAME = "getEconomicValuesMaxLessDate";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teese03Econvalue> result = null;
        EconomicValueDao dao = new EconomicValueDao();

        try {
            result = dao.economicValuesUpdatedFindLessDateQuery(ecoV,
                    periodSelec);
        } catch (PersistenceException e) {
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Item.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    public Collection getEconomicValuesMaxPeriodDate(Teese03Econvalue ecoV) {
        String METHOD_NAME = "getEconomicValuesMaxPeriodDate";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teese03Econvalue> result = null;
        EconomicValueDao dao = new EconomicValueDao();
        try {
            result = dao.economicValuesMaxPeriodQuery(ecoV);
        } catch (PersistenceException e) {
            // TODO: Informar error con los labels y tirar exepcion para arriba
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

}
